//
//  NSDate+sinaDate.swift
//  01-新浪时间处理
//
//  Created by 大波 on 16/3/9.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import Foundation


extension NSDate {
    
    /// 新浪服务器返回时间的格式
    class func sinaDateStringToDate(date: String) -> NSDate {
        
        let dateFormatter = NSDateFormatter()
        
        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        
        dateFormatter.locale = NSLocale(localeIdentifier: "EN")
        
        return dateFormatter.dateFromString(date) ?? NSDate()
    }
    
    
    func dateDescription() -> String {
        
        let calendar = NSCalendar.currentCalendar()
        
        if calendar.isDateInToday(self) {
            
            // 创建当前时间
            let currentDate = Int(NSDate().timeIntervalSinceDate(self))
            
            if currentDate < 60 {
                
                return "刚刚"
                
            } else if currentDate < 60 * 60 {
                
                return "\(currentDate / 60)分钟前"
                
            } else {
                
                return "\(currentDate / 60 / 60)小时前"
            }
        }
        
        var fm = ""
        
        if calendar.isDateInYesterday(self) {
            
            fm = "昨天 HH:mm"
            
        } else if calendar.compareDate(self, toDate: NSDate(), toUnitGranularity: NSCalendarUnit.Year) == NSComparisonResult.OrderedAscending {
            
            fm = "yyyy-MM-dd HH:mm"
            
        } else if calendar.compareDate(self, toDate: NSDate(), toUnitGranularity: NSCalendarUnit.Year) == NSComparisonResult.OrderedSame {
            
            fm = "MM-dd HH:mm"
        }
        
        // 将格式转成时间
        let dateFormatter = NSDateFormatter()
        
        dateFormatter.dateFormat = fm
        
        dateFormatter.locale = NSLocale(localeIdentifier: "EN")
        
        return dateFormatter.stringFromDate(self)
    }
}






